package com.atsmart.app.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.InstrumentedActivity;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.ClientListInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.LocationPageinfo;
import com.atsmart.app.model.PageInfo;
import com.atsmart.app.model.ResultInfo;
import com.atsmart.app.model.VersionInfo;
import com.atsmart.app.model.VersionListInfo;
import com.atsmart.app.service.CheckingService;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.JgpushUtil;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.utils.UpdateUtils;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.google.json.JsonSyntaxException;

/**
 * TODO 应用预处理界面
 */
public class WelcomeActivity extends InstrumentedActivity implements
		TagAliasCallback {
	private String newVerName = "";// 新版本名称
	private int newVerCode = -1;// 新版本号
	private static ProgressDialog pd = null;
	private static String UPDATE_SERVERAPK = "biz.apk";
	private String url = "";// 新版本url
	private Thread th = null;
	private static boolean flag = false;
	private Context context;

	private String time;

	public Boolean Loading = true;
	public Boolean ff = false;
	Dialog dialog;
	int forcing = 0;

	public static boolean isForeground = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome_layout);

		// TODO
//		Log.e("推送初始化", "开始推送初始化");
		new Thread() {
			public void run() {
				init();// 推送init
				// registerMessageReceiver(); // 极光推送消息
				setTag();
				setStyleCustom();
				// setAlias();
				JPushInterface.resumePush(getApplicationContext());
			};
		}.start();

		Log.e("推送初始化", "结束推送初始化");

		context = this;

		time = StringUtil.getCurrentTime();

		pd = new ProgressDialog(WelcomeActivity.this);
		// pd.setTitle("正在连接服务器");
		pd.setMessage("连接中,请稍后...");
		Window window = pd.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.y = 120;
		window.setAttributes(lp);
		pd.show();

	}

	private boolean is_push_up = false;
	@Override
	protected void onResume() {
		super.onResume();
		isForeground = true;
//		Log.e(TAG, "是否更新: = " + PrefsUtils.getIsPushUp());
//		if(!StringUtil.isEmptyOrNull(PrefsUtils.getIsPushUp())){
//			is_push_up = true;
//		}else{
//			is_push_up = false;
//		}
		// 发起定位，设置定位监听
		BizApp.getInstance().getmLocationClient().start();
		// 无网络状态下设置用户不可用
		if (BizApp.getInstance().isWiFiActive()
				|| BizApp.getInstance().isNetworkAvailable()) {
			new AsyncTask<Void, Void, Void>() {
				@Override
				protected Void doInBackground(Void... params) {
					if (is_push_up) {
						keep();
					} else {
						keeps();
					}
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					// sleepToNextPage();
				}
			}.execute();
		} else {
			PrefsUtils.setUserState(String
					.valueOf(PersistentKeyUtil.UN_NORMAL_USER_STATE));
			Toast.makeText(context, "无可用网络！", Toast.LENGTH_SHORT).show();
			sleepToNextPage();
		}
	}

	private Handler dialogHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0x201) {
				doNewVersionUpdate();// 更新版本
			}
		};
	};

	private boolean keep() {
		try {
//			Log.e(TAG, "执行更新协议！");
//			getServerVer();
			int count = 0;
			try {
				while (!ff && count < 6) {
					Thread.sleep(1000);
					count++;
				}
			} catch (InterruptedException e) {
			}
			BizApp.getInstance().keeping = true;
			if (!ff) {
				BizApp.getInstance().keeping = false;
				sleepToNextPage();
			}

			return true;
		} catch (Exception e) {
			// Log.e("welcom", "keep is exception");
			e.printStackTrace();
			BizApp.getInstance().keeping = false;
			sleepToNextPage();
			return false;
		}

	}
	
	private boolean keeps() {
		try {
			BizApp.getInstance().keeping = true;
			sleepToNextPage();
			return true;
		} catch (Exception e) {
			// Log.e("welcom", "keep is exception");
			e.printStackTrace();
			BizApp.getInstance().keeping = false;
			sleepToNextPage();
			return false;
		}

	}

	private void sleepToNextPage() {
		new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... params) {
				// Log.e("tag", "跳转到lognin");
				SystemClock.sleep(2000);
				IntentUtil.redirectToNext(WelcomeActivity.this,
						LoginActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
				WelcomeActivity.this.finish();

				return null;
			}
		}.execute();
	}

	/**
	 * 获得版本号
	 */
	public int getVerCode(Context context) {
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo(
					"com.atsmart.app", 0).versionCode;
		} catch (NameNotFoundException e) {
			// Log.e("版本号获取异常", e.getMessage());
		}
		return verCode;
	}

	/**
	 * 获得版本名称
	 */
	public String getVerName(Context context) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo(
					"com.atsmart.app", 0).versionName;
		} catch (NameNotFoundException e) {
			// Log.e("版本名称获取异常", e.getMessage());
		}
		return verName;
	}

	private void dealwithResult(VersionListInfo result) {

		if (result != null) {
			List<VersionInfo> verlist = result.getVers();
			if (verlist != null && verlist.size() > 0) {
				VersionInfo ver = verlist.get(0);
				newVerCode = ver.getCode();
				newVerName = ver.getVersion();
				url = ver.getUrl();
				forcing = ver.getForcing();

				int verCode = this.getVerCode(this);
				if (newVerCode > verCode) {
					UPDATE_SERVERAPK = "biz" + newVerCode + "_" + newVerName
							+ ".apk";
					pd.dismiss();
					pd.cancel();
					Message msg = new Message();
					msg.what = 0x201;
					dialogHandler.sendMessage(msg);

				} else {

					sleepToNextPage();
				}
			}
		} else {

			if (!StringUtil.isEmptyOrNull(PrefsUtils.getResult())) {
				PrefsUtils.setRegisteredPhone(null);
				PrefsUtils.setRegisteredImsi(null);
				PrefsUtils.setRegisteredImsi(null);
				if (BizApp.getInstance().isServiceRun()) {
				}
			}
			sleepToNextPage();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// unregisterReceiver(mMessageReceiver);
		if (pd != null)
			pd.dismiss();
		flag = false;
	}

	/**
	 * 更新版本
	 */
	public void doNewVersionUpdate() {

		String verName = this.getVerName(this);
		StringBuffer sb = new StringBuffer();
		sb.append("当前版本：");
		sb.append(verName);
		// sb.append(" Code:");
		// sb.append(verCode);
		sb.append(",发现版本：");
		sb.append(newVerName);
		// sb.append(" Code:");
		// sb.append(verCode);
		sb.append(",是否更新");
		flag = true;

		if (forcing == 0) {
			dialog = new AlertDialog.Builder(this)
					.setTitle("软件更新")
					.setMessage(sb.toString())
					.setPositiveButton("现在更新",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									pd.dismiss();
									pd.cancel();
									pd = new ProgressDialog(
											WelcomeActivity.this);
									pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
									pd.setMessage("正在下载更新，请稍候...");
									pd.setCancelable(true);
									pd.setOnCancelListener(new OnCancelListener() {
										public void onCancel(
												DialogInterface arg0) {
											flag = false;
											finish();
										}
									});
									// downFile(url);
									pd.show();
									if (th != null) {
										th.stop();
									}
									new Thread() {
										public void run() {

											GetFileFromUrl(
													url,
													Environment
															.getExternalStorageDirectory()
															+ "/atsmart"
																	.toString());
										}
									}.start();
								}
							})
					.setNegativeButton("暂不更新",
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									// toNextPage();
									sleepToNextPage();
									finish();
								}
							}).create();
		} else {
			dialog = new AlertDialog.Builder(this)
					.setTitle("软件更新")
					.setMessage(sb.toString())
					.setPositiveButton("现在更新",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									pd.dismiss();
									pd.cancel();
									pd = new ProgressDialog(
											WelcomeActivity.this);
									pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
									pd.setMessage("正在下载更新，请稍候...");
									pd.setCancelable(true);
									pd.setOnCancelListener(new OnCancelListener() {
										public void onCancel(
												DialogInterface arg0) {
											flag = false;
											finish();
										}
									});
									// downFile(url);
									pd.show();
									if (th != null) {
										th.stop();
									}
									new Thread() {
										public void run() {

											GetFileFromUrl(
													url,
													Environment
															.getExternalStorageDirectory()
															.toString()
															+ "/atsmart");
										}
									}.start();
								}
							}).create();
		}
		// 显示更新框
		dialog.show();

	}

	public Boolean GetFileFromUrl(String url, String path) {

		long curPosition = 0;
		long startPosition = 0;
		long endPosition = 0;
		long downloadSize = 0;

		long fileLength = 0;
		long localFileLength = 0;

		byte[] b = new byte[51200];

		long progress = 0; // 进度

		URL urlx = null;
		HttpURLConnection con = null;
		InputStream stream = null;

		File file = null;
		RandomAccessFile fos = null;

		File fPath = new File(path);
		if (!fPath.exists())
			fPath.mkdirs();

		file = new File(path, UPDATE_SERVERAPK);
		System.out.println(path + " " + UPDATE_SERVERAPK);
		try {
			fos = new RandomAccessFile(file, "rwd");
			startPosition = fos.length();

			Log.d("URL:", url);
			urlx = new URL(url);
			con = (HttpURLConnection) urlx.openConnection();
			con.setAllowUserInteraction(true);
			con.setConnectTimeout(10 * 1000);
			con.setReadTimeout(10 * 1000);
			con.setRequestMethod("GET");
			con.setRequestProperty("Referer", url);
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Range", "bytes=" + startPosition + "-");// 设置获取实体数据的范围
			con.setRequestProperty("Connection", "Keep-Alive");
			fileLength = con.getContentLength();
			Log.i("tag", "filelenth:" + fileLength);
			if (fileLength == -1) {
				Log.i("tag", "ERROR:" + url + "文件不存在");
				return false;
			}
			endPosition = startPosition + fileLength;

			int code = con.getResponseCode();
			if (code == 416) {
				localFileLength = file.length();
				Log.i("tag", "size:" + localFileLength);

				if (startPosition == localFileLength) {
					Log.i("tag", "OK");
					down();
					return true;
				}
			}
			if (code == HttpURLConnection.HTTP_OK || code == 206) {
				stream = con.getInputStream();

				localFileLength = file.length();
				Log.i("tag", "size:" + localFileLength);

				downloadSize += startPosition;

				curPosition = startPosition;
				fos.seek(startPosition);
				int count = 0;
				while (curPosition < endPosition && flag) {
					int len = stream.read(b, 0, 51200);

					if (len == -1)
						break;
					// fos.setLength(curPosition + len);
					fos.write(b, 0, len);

					curPosition = curPosition + len;

					if (curPosition > endPosition) {
						downloadSize += len - (curPosition - endPosition);
					} else {
						downloadSize += len;
					}
					count++;
					if (count > 20) {
						count = 0;
						fos.close();
						fos = new RandomAccessFile(file, "rwd");
						fos.seek(curPosition);

					}
					progress = (long) (((float) downloadSize / endPosition) * 100);
					Log.i("tag", "progress" + progress);
					Message msg = handler.obtainMessage();
					msg.getData().putInt("step", (int) (progress));
					handler.sendMessage(msg);
				}

				stream.close();
				fos.close();
				con.disconnect();
				if (progress == 100)
					down();

			}
		} catch (Exception e) {
			// Log.e("exception : ", e.getMessage() + "");
			b = null;
		} finally {
			if (pd != null) {
				pd.dismiss();
			}
			try {
				if (stream != null) {
					stream.close();
				}
			} catch (Exception e) {
				// Log.e("exception : ", e.getMessage());

			}

		}
		return true;
	}

	final private static Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int nStep = msg.getData().getInt("step", -1);
			if (nStep == -1) {
				pd.dismiss();
			} else {
				pd.setProgress(nStep);
			}
		}
	};

	/**
	 * 下载完成，通过handler将下载对话框取消
	 */
	public void down() {
		update();
		Message message = handler.obtainMessage();
		handler.sendMessage(message);

	}

	/**
	 * 安装应用
	 */
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		PrefsUtils.setIsPushUp(null);
		intent.setDataAndType(
				Uri.fromFile(new File(Environment.getExternalStorageDirectory()
						.toString() + "/atsmart", UPDATE_SERVERAPK)),
				"application/vnd.android.package-archive");
		startActivity(intent);

	}

	/**
	 * 从服务器端获得版本号与版本名称
	 * 
	 * @return
	 * @throws Exception
	 * @throws BizException
	 * @throws IOException
	 * @throws AssertionError
	 * @throws JsonSyntaxException
	 */
	public void getServerVer() throws Exception {
		new ServiceAsynTask<VersionListInfo>() {

			@Override
			protected VersionListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException, Exception {
				PageInfo pageInfo = new PageInfo();
				pageInfo.begin = 1;
				pageInfo.end = 1;
				return ServiceHelper.getInstance().postData(
						ServiceHost.versionLocationURL(),
						new Gson().toJson(pageInfo), VersionListInfo.class);
			}

			@Override
			protected void runWithResult(VersionListInfo result)
					throws Exception {
				dealwithResult(result);
				ff = true;
			}

			@Override
			protected void runWithError(VersionListInfo result, int iErrorCode)
					throws Exception {
				BizApp.getInstance().keeping = false;
				// sleepToNextPage();
				ff = false;

			}
		}.execute();
	}

	// TODO
	/**
	 * 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
	 */
	private void init() {
		JPushInterface.init(getApplicationContext());
	}

	/**
	 * 设置设备标签TAG
	 */
	private void setTag() {
		// 检查 tag 的有效性
		String tag = BizApp.getInstance().getIMSI();
//		Log.e("TAG", "tag: = " + tag);
		// ","隔开的多个 转换成 Set
		if(!StringUtil.isEmptyOrNull(tag)){
			String[] sArray = tag.split(",");
			Set<String> tagSet = new LinkedHashSet<String>();
			for (String sTagItme : sArray) {
				if (!JgpushUtil.isValidTagAndAlias(sTagItme)) {
	//				Log.e("ceshi", "tag is null");
					return;
				}
				tagSet.add(sTagItme);
			}
	
			// 调用JPush API设置Tag
			JPushInterface.setAliasAndTags(getApplicationContext(), null, tagSet,
					this);
		}else{
			Message msg = new Message();
			msg.what = 0x102;
			handler2.sendMessage(msg);
		}

	}

	private Handler handler2 = new Handler(){
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what == 0x102){
				Toast.makeText(context, "获取手机IMSI号失败", Toast.LENGTH_SHORT).show();
			}
		};
	};
	/**
	 * 设置通知栏样式 - 定义通知栏Layout
	 */
	private void setStyleCustom() {
		CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(
				WelcomeActivity.this, R.layout.customer_notitfication_layout,
				R.id.icon, R.id.title, R.id.text);
		builder.statusBarDrawable = R.drawable.icon;
		builder.notificationDefaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
		// builder.developerArg0 = "developerArg2";
		// JPushInterface.setPushNotificationBuilder(0, builder);
		JPushInterface.setDefaultPushNotificationBuilder(builder);// 设置默认标题栏样式
//		Log.e("TAG", "标题栏样式");
	}

	/**
	 * 设置Alias
	 */
	// private void setAlias() {
	// String alias = "26";
	// if (StringUtil.isEmptyOrNull(alias)) {
	// Log.e(TAG, "alias is empty");
	// return;
	// }
	// if (!JgpushUtil.isValidTagAndAlias(alias)) {
	// Log.e(TAG, "alias 无效， 不是数字/字母/中文");
	// return;
	// }
	//
	// // 调用JPush API设置Alias
	// JPushInterface.setAliasAndTags(getApplicationContext(), alias, null,
	// this);
	// }

	// for receive customer msg from jpush server
	// private MessageReceiver mMessageReceiver;
	// public static final String MESSAGE_RECEIVED_ACTION =
	// "com.atsmart.app.activity.MESSAGE_RECEIVED_ACTION";
	// public static final String KEY_TITLE = "title";
	// public static final String KEY_MESSAGE = "message";
	// public static final String KEY_EXTRAS = "extras";
	//
	// /** 推送消息 */
	// public void registerMessageReceiver() {
	// mMessageReceiver = new MessageReceiver();
	// IntentFilter filter = new IntentFilter();
	// filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
	// filter.addAction(MESSAGE_RECEIVED_ACTION);
	// registerReceiver(mMessageReceiver, filter);
	// }
	//
	// public class MessageReceiver extends BroadcastReceiver {
	//
	// @Override
	// public void onReceive(Context context, Intent intent) {
	// if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
	// String messge = intent.getStringExtra(KEY_MESSAGE);
	// String extras = intent.getStringExtra(KEY_EXTRAS);
	// StringBuilder showMsg = new StringBuilder();
	// showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
	// if (!JgpushUtil.isEmpty(extras)) {
	// showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
	// }
	// setCostomMsg(showMsg.toString());
	// }
	// }
	// }
	//
	// private void setCostomMsg(String msg) {
	// if (StringUtil.isEmptyOrNull(msg)) {
	// Log.e("接受发到消息", "消息为null");
	// } else {
	// Log.e("接受发到消息", msg);
	// }
	// }

	private static final String TAG = WelcomeActivity.class.getName();

	public void gotResult(int code, String alias, Set<String> tags) {
		String logs;
		switch (code) {
		case 0:
			logs = "Set tag and alias success, alias = " + alias + "; tags = "
					+ tags;
			Log.e(TAG, logs);
			break;

		default:
			logs = "Failed with errorCode = " + code + " " + alias
					+ "; tags = " + tags;
			Log.e(TAG, logs);
		}

	}
}
